﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ClientSandboxie.cs;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace ClientSandboxie
{
    public partial class Form1 : Form
    {
        
      //  private string localip;
      //  IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName());
        //User user;
        public TcpClient client;
        public BinaryReader br;
        public BinaryWriter bw;
        public NetworkStream networkStream;
        public bool isExit=false;
       

        //定义鼠标操作：Pointer鼠标指针、Rectangle矩形、count工具的个数
        public enum ToolType { Pointer, ArrowCurve,Image, Text, Curve, count };
        public ToolType activeTool;
        ToolObject[] tools = new ToolObject[(int)ToolType.count];
        public Form1()
        {
            InitializeComponent();
            CC.userCtrl = userControl11;
            tools[(int)ToolType.Pointer] = new ToolPointer();
            //tools[(int)ToolType.Rectangle] = new ToolRectangle();
            tools[(int)ToolType.Image] = new ToolImage();
            tools[(int)ToolType.ArrowCurve] = new ToolArrowCurve();  
            tools[(int)ToolType.Curve] = new ToolCurve();
            tools[(int)ToolType.Text] = new ToolText();
        }

        private void buttonArrowCurve_Click(object sender, EventArgs e)
        {
            activeTool = ToolType.ArrowCurve;
        }

        private void buttonCurve_Click(object sender, EventArgs e)
        {
            activeTool = ToolType.Curve;
        }

        private void userControl11_MouseDown(object sender, MouseEventArgs e)
        {
            userControl11.Capture = false;
            if (e.Button == MouseButtons.Left)
            {
                tools[(int)activeTool].OnMouseDown(e);
            }
            else if (e.Button == MouseButtons.Right)
            {
                activeTool = ToolType.Pointer;
            }
        }

        private void userControl11_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left || e.Button == MouseButtons.None)
            {
                tools[(int)activeTool].OnMouseMove(e);
            }
            else
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void userControl11_MouseUp(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Left)
            {
                tools[(int)activeTool].OnMouseUp(e);
            }
        }

        private void userControl11_Paint(object sender, PaintEventArgs e)
        {

            Graphics g = e.Graphics;
            DrawObject w;
            for (int i = 0; i < CC.graphicsList.Count; i++)
            {
                w = CC.graphicsList[i];
                if (w.IntersectsWith(Rectangle.Round(g.ClipBounds)))
                {
                    w.Draw(g);
                }
                //绘制句柄
                if (w.Selected == true)
                {
                    w.DrawTracker(g);
                }
            }
            //画鼠标左键拖放范围的选择框
            if (CC.IsDrawNetRectangle == true)
            {
                ControlPaint.DrawFocusRectangle(e.Graphics, CC.NetRectangle, Color.Black, Color.Transparent);
            }
        }
     

        private void buttonText_Click(object sender, EventArgs e)
        {
            TextDialog td = new TextDialog();
            if (td.ShowDialog() == DialogResult.OK)
            {
                CC.textInfo.text = td.MyText;
                CC.textInfo.color = td.MyColor;
                activeTool = ToolType.Text;
            }
        }

        private void buttonSelect_Click(object sender, EventArgs e)
        {

            CC.SelectAll();
            activeTool = ToolType.Pointer;
        }
        /// <summary>
        /// 建立连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            try
            {
                //localip = ip[ip.Length - 1].ToString();
                client = new TcpClient();
                client.Connect("192.168.1.23", 8888);
               
                textBoxConnect.Text = "本机为附机，主机ip为" + "192.168.1.23";
                AddTalkMessage("连接成功");
            }
            catch
            {
                MessageBox.Show("连接失败");
                return;
            }
         
            networkStream = client.GetStream();
            bw = new BinaryWriter(networkStream);
            br = new BinaryReader(networkStream);
            SendMessage("Login," + textBoxUserName.Text);
           
            Thread threadReceive = new Thread(new ThreadStart(ReceiveData));
            threadReceive.IsBackground = true;
            threadReceive.Start();
            
           
            

        }

        public void SendMessage(string sendStr)
        {
            try
            {
                bw.Write(sendStr);
                bw.Flush();
            }
            catch
            {
                AddTalkMessage("发送失败！");
            }
        }
        /// <summary>
        /// 处理接收的服务器数据
        /// </summary>
        public void ReceiveData()
        {
            string receiveStr = null;
            while (isExit == false)
            {
                try
                {
                    receiveStr = br.ReadString();

                }
                catch
                {
                    if (isExit == false)
                    {
                        MessageBox.Show("与服务器失去联系");
                    }
                    break;
                }
                string[] splitString = receiveStr.Split(',');
                string command = splitString[0].ToLower();
                switch (command)
                {
                    case "login":// 格式：login，用户名
                        AddOnline(splitString[1]);
                        break;
                    case "logout":// 格式：logout，用户名
                        RemoveUser(splitString[1]);
                        break;
                    case "talk": // 格式：talk，用户名,对话信息
                        AddTalkMessage(splitString[1] +"说"+ ":");
                        AddTalkMessage(receiveStr.Substring(splitString[0].Length + splitString[1].Length + 2));
                        break;
                    default:
                        AddTalkMessage("什么意思啊" + receiveStr);
                        break;

                }
             }
            Application.Exit();
       
         }
/// <summary>
/// 增加在线的用户信息
/// </summary>
/// <param name="message"></param>
        private delegate void AddOnlineDelegate(string message);
        private void AddOnline(string userName)
        {
            if (listBoxUser.InvokeRequired)
            {
                AddOnlineDelegate d = new AddOnlineDelegate(AddOnline);
                listBoxUser.Invoke(d, new object[] { userName});
            }
            else
            {
                listBoxUser.Items.Add(userName);
                listBoxUser.SelectedIndex = listBoxUser.Items.Count - 1;
                listBoxUser.ClearSelected();
            }
        }
        /// <summary>移除不在线的用户 </summary>
        private delegate void RemoveUserDelegate(string userName);
        private void RemoveUser(string userName)
        {
            if (listBoxUser.InvokeRequired)
            {
                RemoveUserDelegate d = RemoveUser;
                listBoxUser.Invoke(d, userName);
            }
            else
            {
                listBoxUser.Items.Remove(userName);
                listBoxUser.SelectedIndex = listBoxUser.Items.Count - 1;
                listBoxUser.ClearSelected();
            }
        }
        /// <summary>
        /// 添加会话信息
        /// </summary>
        /// <param name="message"></param>
        private delegate void AddTalkMessageDelegate(string message);
        private void AddTalkMessage(string message)
        {
            if (listBoxInfo.InvokeRequired)
            {
                AddTalkMessageDelegate d = new AddTalkMessageDelegate(AddTalkMessage);
                listBoxInfo.Invoke(d, new object[] { message });
            }
            else
            {
                listBoxInfo.Items.Add(message);

            }
        }
        private void button7_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            CC.bitmap = (Bitmap)Bitmap.FromFile("C:\\Users\\Administrator\\Desktop\\our-project-csharp\\trunk\\ClientSandboxie\\ClientSandboxie\\images\\Junqi.png",true);
            activeTool = ToolType.Image;
        }

        private void buttonTanke_Click(object sender, EventArgs e)
        {
            CC.bitmap = (Bitmap)Bitmap.FromFile("C:\\Users\\Administrator\\Desktop\\our-project-csharp\\trunk\\ClientSandboxie\\ClientSandboxie\\images\\Tanke.png", true);
            activeTool = ToolType.Image;
        }

        private void buttonSenlin_Click(object sender, EventArgs e)
        {
            CC.bitmap = (Bitmap)Bitmap.FromFile("C:\\Users\\Administrator\\Desktop\\our-project-csharp\\trunk\\ClientSandboxie\\ClientSandboxie\\images\\草丛.png", true);
            activeTool = ToolType.Image;
        }
        /// <summary>
        /// 发送会话信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSend_Click(object sender, EventArgs e)
        {
            SendMessage("Talk,"+textBoxUserName.Text+","+textBoxSend.Text);
            textBoxSend.Clear();
            
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //未与服务器连接之前，client为空
            if (client != null)
            {
                SendMessage("Logout," + textBoxUserName.Text);
                isExit = true;
                br.Close();
                bw.Close();
                client.Close();
            }
        }


    }
}
